package main

import (
	"log"
	"runtime"

	"math/rand"
	"time"

	"github.com/streadway/amqp"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

// 只能在安装 rabbitmq 的服务器上操作
func main() {
	runtime.GOMAXPROCS(2)
	conn, err := amqp.Dial("amqp://guest:guest@192.168.3.218:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"hello", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	failOnError(err, "Failed to declare a queue")

	msgs, err := ch.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	failOnError(err, "Failed to register a consumer")

	forever := make(chan bool)
	log.Printf("runtime.NumGoroutine=%d", runtime.NumGoroutine())

	go func() {
		for d := range msgs {
			sleepTime := rand.Intn(100) * 100000000
			time.Sleep(time.Duration(sleepTime))
			log.Printf("0. Received a message: %s,,,sleepTime=%d", d.Body, sleepTime)
		}
	}()
	log.Printf("runtime.NumGoroutine=%d", runtime.NumGoroutine())
	go func() {
		for d := range msgs {
			// sleepTime := rand.Intn(100) * 100000000
			// time.Sleep(time.Duration(sleepTime))
			log.Printf("1. Received a message: %s,,,sleepTime=%d", d.Body, runtime.NumGoroutine())
		}
	}()
	log.Printf("runtime.NumGoroutine=%d", runtime.NumGoroutine())
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}
